﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Fis.Win.Forms
{
    public partial class AccountEditForm : EditForm
    {
        public AccountEditForm()
        {
            InitializeComponent();
        }

        public override void InitializeBinding()
        {
            var d = ViewModel["viewData"] as DataTable;
            ViewModel["Action"] = ViewState.ToString();

            //新建初始化
            if (ViewState == Agile.Engine.View.ViewState.AddNew)
            {
                var r = d.Rows[0];
                r["FJD"] = "1";
                r["FWBHS"] = "0";
                r["FBZ"] = "defaultCurrencyRate";
                r["FQUANTITY"] = "0";
                r["FFIXEDACCOUNT"] = "0";
            }
            edCode.Properties.ReadOnly = (ViewState != Agile.Engine.View.ViewState.AddNew);


            edCode.DataBindings.Add("EditValue", d, "FCODE");
            edCode.Focus();
            edName.DataBindings.Add("EditValue", d, "FNAME");
            edKind.DataBindings.Add("EditValue", d, "FTYPE");
            edDirect.DataBindings.Add("EditValue", d, "FJD");
            edCurrency.DataBindings.Add("EditValue", d, "FBZ");
            edCurAids.DataBindings.Add("EditValue", d, "FWBHS");
            edAids.DataBindings.Add("EditValue", d, "FFZHS");
            edNumber.DataBindings.Add("EditValue", d, "FQUANTITY");
            edUnit.DataBindings.Add("EditValue", d, "FUNIT");



            Fis.Win.Utils.UIUtils.LookUpBinding(edKind, Fis.Win.Utils.CacheContext.GetCache("accSystem"), "caption", "key");
            Fis.Win.Utils.UIUtils.LookUpBinding(edCurrency, Fis.Win.Utils.CacheContext.GetCache("TRATE"), "FNAME", "SID");
            Fis.Win.Utils.UIUtils.LookUpBinding(edDirect, Fis.Win.Utils.CacheContext.DebitCreditCache(), "display", "value");
            Fis.Win.Utils.UIUtils.LookUpBinding(edCurAids, Fis.Win.Utils.CacheContext.WBHSCache(), "display", "value");

            edAids.Properties.DataSource = Fis.Win.Utils.CacheContext.GetCache("aidsgroup");
            edAids.Properties.DisplayMember = "caption";
            edAids.Properties.ValueMember = "key";

        }

        protected override bool SaveProcess()
        {
            ///级次
            var level = Fis.Win.Utils.AppSession.Book["FACCSTRUCT"];

            if (!ValidAccountLevel(level.ToString(), edCode.EditValue.ToString()))
            {
                return false;
            }

            var data = ViewModel["viewData"] as DataTable;
            var accData = Fis.Win.Utils.CacheContext.GetCache("TACCOUNT");
            var count = accData.Compute("COUNT(SID)", string.Format("FPARENT='{0}'", data.Rows[0]["FPARENT"]));

            //第一个子级科目
            if (Agile.Engine.Utils.DataUtils.Parse(0, count) <= 0)
            {
                var msg = "新建完成后会将上级科目本年的业务数据全部转移到本科目，是否继续？";
                var mr = DevExpress.XtraEditors.XtraMessageBox.Show(msg, "提示", MessageBoxButtons.YesNo);
                if (mr == System.Windows.Forms.DialogResult.No)
                    return false;
            }

            ///失败
            if (!ViewProvider.ExecuteUpdate(ViewModel))
            {
                return false;
            }

            Fis.Win.Utils.CacheContext.RefreshCache("TACCOUNT");
            Message = "保存成功";
            return true;
        }

        protected override void InitializeAfterSave()
        {
            var data = ViewModel["viewData"] as DataTable;
            //var code = Fis.Win.Utils.CacheContext.GetCache("TACCOUNT").Compute("MAX(FCODE)"
            //    , string.Format("FPARENT='{0}'", data.Rows[0]["SID"]));
            var row = data.NewRow();
            row.ItemArray = data.Rows[0].ItemArray;
            row["FCODE"] = (Convert.ToInt32(row["FCODE"].ToString()) + 1).ToString();
            row["SID"] = string.Empty;
            row["FNAME"] = string.Empty;

            ViewModel = ViewProvider.InitializeViewModel(Agile.Engine.Utils.DataUtils.ToEditModel("viewData", row));
            Fis.Win.Utils.UIUtils.ClearBindings(layoutControl1);
            InitializeBinding();
        }

        bool ValidAccountLevel(string level, string code)
        {
            var l = level.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);

            var len = 0;
            var parent = string.Empty;
            for (var i = 0; i < l.Length; i++)
            {
                len += int.Parse(l[i]);
                if (len > code.Length)
                {
                    Message = string.Format("科目编码结构错误，请参照{0}", level);
                    return false;
                }
                var c = code.Substring(0, len);

                //一级科目
                if (code.Length == len)
                {
                    break;
                }

                if (i != l.Length - 1)
                {
                    var acc = Fis.Win.Utils.CacheContext.GetCache("TACCOUNT").Select(string.Format("FCODE='{0}'", c));
                    if (acc.Length > 0)
                    {
                        parent = acc[0]["SID"].ToString();
                    }
                    else
                    {
                        Message = string.Format("上级科目{0}不存在", c);
                        return false;
                    }
                }
                else
                {
                    Message = string.Format("科目编码结构错误，请参照{0}", level);
                    return false;
                }
            }

            var d = (ViewModel["viewData"] as DataTable).Rows[0];

            d["FPARENT"] = parent;
            d["FISFZHS"] = IsFzhsAccount();
            d["FDETAILNAME"] = string.Format("{0}-{1}", edCode.EditValue, edName.EditValue);

            return true;
        }

        string IsFzhsAccount()
        {
            if (edCurAids.EditValue.ToString() != "0"
                || !Agile.Engine.Utils.StringUtils.IsEmpty(edAids.EditValue)
                || edNumber.EditValue.ToString() != "0")
                return "1";

            return "0";
        }

        private void edCode_EditValueChanged(object sender, EventArgs e)
        {
            if (Agile.Engine.Utils.StringUtils.IsEmpty(edCode.EditValue))
                return;

            var value = edCode.EditValue.ToString();
            var d = (ViewModel["viewData"] as DataTable).Rows[0];
            d["FTYPE"] = value.Substring(0, 1);
            d["FCODE"] = value;
        }

        private void edCurrency_EditValueChanged(object sender, EventArgs e)
        {
            edCurAids.Enabled = edCurrency.EditValue.ToString() != Fis.Win.Utils.CacheContext.DefaultCurrencyRate;
        }

        private void edNumber_CheckedChanged(object sender, EventArgs e)
        {
            edUnit.Enabled = edNumber.Checked;

            if (edUnit.Enabled)
            {
                edUnit.Focus();
            }
        }

        private void edCurrency_Properties_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)
            {
                var v = UIManager.ShowEdit<RateEditForm>("RateEditViewProvider", Agile.Engine.View.ViewState.AddNew);
                if (((DialogResult)v.ViewResult) == System.Windows.Forms.DialogResult.OK)
                {
                    Fis.Win.Utils.CacheContext.RefreshCache(v.ViewProvider.DataTableName);
                    Fis.Win.Utils.UIUtils.LookUpBinding(edCurrency, Fis.Win.Utils.CacheContext.GetCache("TRATE"), "FNAME", "SID");
                    edCurrency.EditValue = (v.ViewModel["viewData"] as DataTable).Rows[0]["SID"];
                }
            }

        }
    }
}
